<template>
  <div class="app-container">
    <div class="operation">
      <el-button
        type="primary"
        style="margin-bottom: 10px"
        @click="
          centerDialogVisible = true;
          type = 1;
        "
        >添加商品分类</el-button
      >
      <el-input
        placeholder="请输入查询字段"
        class="input-with-select"
        style="width: 300px; margin-left: 10px"
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </div>
    <el-table
      v-loading="listLoading"
      :data="shopList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="80px">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.releaseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预览" align="center">
        <template slot-scope="{ row }">
          <el-image
            style="width: 70%; height: 100px"
            :src="`${api}/attachment/preview?attachmentId=${row.carouselIdList[0]}`"
            :preview-src-list="row.carouselIdList | filterUlr"
            fit="cover"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="规格/单价" align="center" width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.commodityPrice + "/" + scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.classifyNameList | filterifyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.details }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详情图" align="center">
        <template slot-scope="{ row }">
          <el-image
            style="width: 70%; height: 100px"
            :src="`${api}/attachment/preview?attachmentId=${row.detailIdList[0]}`"
            :preview-src-list="row.detailIdList | filterUlr"
            fit="cover"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="openSpecifica(row)"
          >
            规格
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="openUpdate(row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-edit"
            @click="deleteShop(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="type ? '新增' : '修改'"
      :visible.sync="centerDialogVisible"
      width="40%"
      @close="clearForm"
      :close-on-click-moda="false"
      center
    >
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        :rules="rules"
        v-if="centerDialogVisible"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="详情" prop="details">
          <el-input v-model="form.details"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="commodityPrice">
          <el-input v-model="form.commodityPrice"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="classifyIdList">
          <el-checkbox-group v-model="checkClass" @change="checkChange">
            <el-checkbox
              :label="itme.id"
              v-for="itme in shopClassList"
              :key="itme.id"
              >{{ itme.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="轮播图" prop="carouselIdList">
          <el-upload
            class="upload-demo"
            :action="`${api}/attachment/upload`"
            accept=".jpg,.png"
            :headers="headerObj"
            :data="uploadData"
            :on-remove="handleRemovecarouse"
            :on-success="upSuccesscarouse"
            :file-list="fileListcarouse"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图" prop="detailIdList">
          <el-upload
            class="upload-demo"
            :action="`${api}/attachment/upload`"
            accept=".jpg,.png"
            :headers="headerObj"
            :data="uploadData"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="upSuccess"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 规格 -->
    <el-dialog
      title="规格"
      :visible.sync="centerspecifica"
      width="40%"
      @close="clearSpecifica"
      :close-on-click-moda="false"
      center
      ><el-form
        ref="form"
        :model="form"
        label-width="80px"
        :rules="rules"
        v-if="centerspecifica"
      >
        <el-form-item label="规格">
          <el-input v-model="specificationInfo.specification"></el-input>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="specificationInfo.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="规格图片" prop="sortNumber">
          <el-upload
            class="avatar-uploader"
            :action="`${api}/attachment/upload`"
            :headers="headerObj"
            accept=".jpg,.png"
            :show-file-list="false"
            :data="uploadData"
            :on-success="upspecifica"
          >
            <img
              v-if="specificationInfo.pictureId"
              :src="`${api}/attachment/preview?attachmentId=${specificationInfo.pictureId}`"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerspecifica = false">取 消</el-button>
        <el-button type="primary" @click="submitSpecifica">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetShopList,
  DeleteShop,
  AddShopInfo,
  GetShopClass,
  SetShopInfo,
  AddSpecification,
} from "@/api/shop";
import { api } from "@/config/index";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      api: api, //服务器地址
      shopList: [],
      centerDialogVisible: false, //弹窗key
      type: 1, //操作类型 1：添加  0：删除
      listLoading: true, //加载
      pageData: {
        //页参
        currPage: 1,
        pageSize: 10,
        searchText: "", //搜索关键字
      },
      classShop: {}, //商品分类数据
      checkClass: [], //选中商品分类数据
      form: {}, //添加/修改的数据
      specification: 1, //规格数量
      specificationInfo: {}, //规格数据
      centerspecifica: false, //规格弹窗
      fileList: [
        //详情图片显示列表
      ],
      fileListcarouse: [], //轮播图片显示列表
      rules: {
        //验证规则
        title: [
          { required: true, message: "请输入商品分类名称", trigger: "blur" },
        ],
        carouselIdList: {
          required: true,
          message: "请上传图片",
          trigger: "blur",
        },
        classifyIdList: {
          required: true,
          message: "请选择分类",
          trigger: "blur",
        },
        commodityPrice: {
          required: true,
          message: "请输入商品价格",
          trigger: "blur",
        },
        details: {
          required: true,
          message: "请输入商品详情",
          trigger: "blur",
        },
        detailIdList: {
          required: true,
          message: "请上传商品详情图",
          trigger: "blur",
        },
        unit: {
          required: true,
          message: "请上传商品单位(如：件/条/个)",
          trigger: "blur",
        },
        commodityPrice: {
          required: true,
          message: "请上传商品单位(如：件/条/个)",
          trigger: "blur",
        },
      },
      headerObj: {
        //获取token
        Authorization: getToken("token"), //携带token
      },
      uploadData: {
        //上传图片的信息
        //上传文件信息
        originalName: "image",
        type: "SLIDESHOW",
      },
    };
  },
  created() {
    this.getShopList();
    this.getShopClass();
  },
  methods: {
    //获取商品列表信息
    getShopList() {
      GetShopList(this.pageData).then((res) => {
        this.shopList = res.data.data_list;
        this.listLoading = false;
      });
    },
    //获取商品分类
    getShopClass() {
      GetShopClass({ currPage: 1, pageSize: 99 }).then((res) => {
        this.shopClassList = res.data.data_list;
        console.log(this.shopClassList);
      });
    },
    //打开修改弹窗
    openUpdate(data) {
      console.log(data);
      this.centerDialogVisible = true;
      this.type = 0;
      this.form = Object.assign({}, data);

      this.checkClass = this.form.classifyNameList.map((itme) => {
        return itme.id;
      });
      this.form.classifyIdList = this.checkClass;
      var data = this.form.detailIdList.map((itme) => {
        return {
          name: itme,
          url: `${api}/attachment/preview?attachmentId=${itme}`,
        };
      });
      this.fileList = data;
      var data2 = this.form.carouselIdList.map((itme) => {
        return {
          name: itme,
          url: `${api}/attachment/preview?attachmentId=${itme}`,
        };
      });
      this.fileListcarouse = data2;
    },
    setShopInfo() {
      SetShopInfo(this.form).then((res) => {
        this.$message.success("修改成功");
        this.centerDialogVisible = false;
        this.getShopList();
      });
    },
    //删除商品
    deleteShop(id) {
      DeleteShop(id).then((res) => {
        this.$message.success("删除成功");
        this.getShopList();
      });
    },
    //清除from 表单
    clearForm() {
      this.form = {};
      this.checkClass = [];
      this.fileList = [];
      this.fileListcarouse = [];
    },
    //清除规格
    clearSpecifica() {
      this.specificationInfo = {};
    },
    //添加商品信息
    addShopInfo() {
      AddShopInfo(this.form).then((res) => {
        this.$message.success("添加成功");
        this.centerDialogVisible = false;
        this.getShopList();
      });
    },
    //打开规格弹窗
    openSpecifica(data) {
      this.specificationInfo.commodityId = data.id;
      this.centerspecifica = true;
    },
    //提交数据
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type) {
            this.addShopInfo(this.form);
          } else {
            console.log(this.form);
            this.setShopInfo();
          }
        } else {
          this.$message.error("请将数据填写完整");
        }
      });
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      if (this.type == 0) {
        var data = fileList.map((itme) => {
          return itme.name;
        });
        this.form.detailIdList = data;
        return false;
      }
      var data = fileList.map((itme) => {
        return itme.response.data.id;
      });
      this.form.detailIdList = data;
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    //详情图片成功的上传时的钩子
    upSuccess(data) {
      if (!Array.isArray(this.form.detailIdList)) {
        this.form.detailIdList = [data.data.id];
      } else {
        this.form.detailIdList.push(data.data.id);
      }
      this.$message.success("图片上传成功");
    },
    handleRemovecarouse(file, fileList) {
      if (this.type == 0) {
        var data = fileList.map((itme) => {
          return itme.name;
        });
        this.form.carouselIdList = data;
        return false;
      }
      var data = fileList.map((itme) => {
        return itme.response.data.id;
      });
      this.form.carouselIdList = data;
    },
    upSuccesscarouse(data) {
      if (!Array.isArray(this.form.carouselIdList)) {
        this.form.carouselIdList = [data.data.id];
      } else {
        this.form.carouselIdList.push(data.data.id);
      }
      console.log(this.form.carouselIdList);
      this.$message.success("图片上传成功");
    },
    //选择分类
    checkChange(data) {
      this.form.classifyIdList = data;
    },
    //添加规格
    submitSpecifica() {
      AddSpecification(this.specificationInfo).then((res) => {
        this.$message.success("添加成功");
        this.centerspecifica = false;
      });
    },
    //上传规格图片
    upspecifica(data) {
      if (data.code == 200) {
        this.$message.success("上传成功");
        console.log(data.data.id);
        this.$set(this.specificationInfo, "pictureId", data.data.id);
      } else {
        this.$message.error("上传失败");
      }
    },
  },
  filters: {
    filterUlr(arrImage) {
      return arrImage.map((itme) => {
        return `${api}/attachment/preview?attachmentId=${itme}`;
      });
    },
    filterifyName(arrName) {
      let arr = [];
      arrName.forEach((element) => {
        arr.push(element.classifyName);
      });
      return arr.join(";");
    },
  },
};
</script>
<style scoped >
.avatar-uploader {
  margin-top: 10px;
}
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

